import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:practice_flutter/utils/http.dart';
import 'package:practice_flutter/utils/logger.dart';
import 'package:practice_flutter/utils/toast.dart';
import 'package:permission_handler/permission_handler.dart'
    as permission_handler;

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String apiKey = 'ec6f580a9ed57f6731978c15a3a50fb1';
  String baseUrl = 'https://restapi.amap.com/v3';

  List nearbyCommunities = [];
  String address = '';

  @override
  void initState() {
    super.initState();

    //  Latitude: 37.4219983, Longitude: -122.084
    // 40.065956, 116.350077
    // queryNearbyCommunities(40.065956, 116.350077);
    // reverseGeocoding(40.065956, 116.350077);
    // getCurrentLocation();
    requestLocationPermission();
  }

  Future<void> requestLocationPermission() async {
    permission_handler.PermissionStatus status =
        await Permission.location.request();
    if (status.isGranted) {
      // 权限未授予
      ToastUtil.showSuccess('位置权限授予');
      _getLocation();
    } else {
      // 权限未授予
      ToastUtil.showError('位置权限未授予');
    }
  }

  void _getLocation() async {
    Location location = Location();
    // 获取当前位置
    try {
      LocationData locationData = await location.getLocation();
      ToastUtil.showSuccess(
          '${locationData.latitude}, ${locationData.longitude}');
      queryNearbyCommunities(locationData.latitude!, locationData.longitude!);
      reverseGeocoding(locationData.latitude!, locationData.longitude!);
    } catch (e) {
      logger.i('获取位置失败：$e');
    }
  }

  Future<void> reverseGeocoding(double latitude, double longitude) async {
    String url =
        '$baseUrl/geocode/regeo?key=$apiKey&location=$longitude,$latitude';
    try {
      var response = await http.get(url);
      // print(response['regeocode']['formatted_address']);
      setState(() {
        address = response['regeocode']['formatted_address'];
      });
    } catch (e) {
      logger.i('查询过程中出现错误: $e');
    }
  }

  Future<void> queryNearbyCommunities(double latitude, double longitude) async {
    String url =
        '$baseUrl/place/around?key=$apiKey&location=$longitude,$latitude&radius=500&types=住宅小区';
    try {
      var response = await http.get(url);
      for (var element in (response['pois'] as List)) {
        // print(element['name']);
        setState(() {
          nearbyCommunities.add(element);
        });
      }
    } catch (e) {
      logger.i('查询过程中出现错误: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('选择社区'),
        ),
        body: ListView(
          padding: const EdgeInsets.all(10),
          children: [
            const Row(
              children: [
                Text(
                  '当前地址',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            Container(
              color: Colors.white,
              padding: const EdgeInsets.all(10),
              child: Row(
                children: [
                  Expanded(child: Text(address)),
                  const Row(
                    children: [
                      Icon(Icons.location_searching_outlined,
                          color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  )
                ],
              ),
            ),
            const SizedBox(height: 10),
            const Row(
              children: [
                Text(
                  '附近社区',
                  style: TextStyle(color: Colors.grey),
                )
              ],
            ),
            const SizedBox(height: 10),
            ListView(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                children: nearbyCommunities
                    .map((item) => GestureDetector(
                          onTap: () {
                            Navigator.pushNamed(context, '/build_list',
                                arguments: {'point': item['name']});
                          },
                          child: Container(
                              color: Colors.white,
                              padding: const EdgeInsets.all(10),
                              child: Row(children: [
                                Expanded(child: Text('${item['name']}')),
                                const Row(children: [
                                  Icon(Icons.arrow_forward_ios,
                                      size: 16, color: Colors.black),
                                ])
                              ])),
                        ))
                    .toList())
          ],
        ));
  }
}
